<template>
  <a-row>
    <div class="total-table-container">
      <a-row style="margin-bottom: 8px;">
        <a-col :span="4">
          <span class="main-title">选择模板</span>
          <a-button class="editable-add-btn" type="primary" @click="toAddPage('new')"
            >+新建模板</a-button
          >
        </a-col>
        <!-- <a-col :span="2" push="18" style="text-align: right;">
          <ExportFile :fetch="getDownloadData" :fields="jsonFields" name="downloadFile.xls">
            <a-button class="editable-add-btn" type="primary" :loading="iconLoading">导出</a-button>
          </ExportFile>
        </a-col> -->
      </a-row>

      <a-row>
        <a-table
          :columns="tableColumns"
          :data-source="tableDataLists"
          :scroll="{ x: 1200 }"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
          :customRow="clickSingleRow"
          :pagination="paginationOpt"
          :loading="isLoading"
          bordered
          @change="handleTableChange"
        >
          <!-- <template slot="leftExt" slot-scope="text, record">
            <a-tooltip placement="right" v-if="record.operateStatus !== 100">
              <template slot="title">
                废除此单
              </template>
              <a-icon type="close-circle" @click.stop="confirmWasteRepairDone(record)" />
            </a-tooltip>
          </template>

          <template slot="kitInformationList" slot-scope="text, record">
            <a-button type="primary" @click.stop="detailPartOrder(record)">查看</a-button>
          </template> -->

          <!-- <template slot="operateBtn" slot-scope="text, record">
            <div class="editable-row-operations">
              <template v-if="record.status == 1">
                <a-button type="primary" @click.stop="confirmOrder(record)">确认收货</a-button>
              </template>
            </div>
          </template> -->
          <template slot="operateBtn" slot-scope="text, record">
            <div style="font-size:18px;">
            <!-- <a-tooltip placement="top" title="修改名称" style="margin-right:8px;">
                <a-icon @click.stop="updateMouldName(text, record)" type="edit" />
              </a-tooltip> -->
              <a-button @click.stop="updateMouldName(text, record)" type="link" >修改名称</a-button>
              <a-button @click.stop="toAddPage('copy',record)" type="link" >复制</a-button>
            <a-popconfirm
              title="确认删除？"
              ok-text="是"
              cancel-text="否"
              @confirm="delMould(text, record)"
            >
              <a-tooltip placement="top" title="删除" style="color:red;" >
                <a-icon @click.stop type="delete" />
              </a-tooltip>
            </a-popconfirm>
            </div>
          </template>
        </a-table>
      </a-row>

      <AddTemplateDialog
        v-if="isAddTemplateDialog"
        :openDialog.sync="isAddTemplateDialog"
        title="创建检查模板"
        :newMouldType="newMouldType"
        :info="rowRecord"
      ></AddTemplateDialog>
      <UpdateNameDialog
        v-if="isUpdateDialogOpen"
        :openDialog.sync="isUpdateDialogOpen"
        :data="data"
        title="修改模板名称"
        @confirmRefreshData="getTableData({ pageNum: paginationOpt.current }, 'tableDataLists')"
      ></UpdateNameDialog>
    </div>
  </a-row>
</template>

<script>
import api from "@/server/mouldConfig.js";
import { buildLinkSelect, getRoleId, filterTableColumns } from "@/unit/tool";
// import { RepairResultType } from '@/unit/constantValue';
import { columns } from "./tableConfig";
// import { AssignRules, FixDoneRules, FinishRules } from './rulesConfig';
import AddTemplateDialog from "./addTemplateDialog";
import ExportFile from "vue-json-excel";
import UpdateNameDialog from "./updateNameDialog.vue";

function buildJsonFields(lists) {
  let jsonFields = {};
  lists.forEach((item, index) => {
    if (item.dataIndex != "operateBtn") {
      jsonFields[item.title] = item.dataIndex;
    }
  });
  return jsonFields;
}

export default {
  name: "machinePartOrderTable",
  props: {
    searchData: Object
  },
  components: {
    AddTemplateDialog,
    ExportFile,
    UpdateNameDialog
  },
  data() {
    return {
      userName: "",
      role: "",
      compId: "",
      newMouldType: 'new',
      tableColumns: [],
      tableDataLists: [],
      isLoading: false,
      isUpdateDialogOpen: false,
      rowRecord: {},
      // detailPartDialog: false,
      isAddTemplateDialog: false,
      paginationOpt: {
        current: 1,
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 8, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showTotal: total => `共 ${total} 条`, // 显示总数
        // 点击分页时事件
        onChange: (current, size) => {
          this.getTableData({ pageNum: current }, "tableDataLists");
        }
      },
      iconLoading: false,
      jsonFields: buildJsonFields(columns)
    };
  },
  computed: {},
  watch: {
    searchData: function(newVal, oldVal) {
      let _this = this;
      _this.getTableData({ pageNum: 1 }, "tableDataLists");
    }
  },
  methods: {
    updateMouldName(text, record) {
      this.data = { ...record };
      this.isUpdateDialogOpen = true;
    },
    delMould(text, record) {
      api.delMould(record.id).then(res => {
        if (res.code == 200) {
          this.getTableData({ pageNum: this.paginationOpt.current }, "tableDataLists");
          console.log("删除成功");
        } else if(res.code == 9000){
          this.$message.error(res.message)
        }else{
          console.log("删除失败");
        }
      });
    },
    // getData(parames) {
    //   this.deliverGoodsInfoGetAll(parames, 'tableDataLists');
    // },
    handleTableChange(pagination) {
      this.paginationOpt.current = pagination.current;
    },
    // Table 获取数据
    async getTableData(parames, key) {
      let _this = this;
      let { pageNum } = parames;
      // let {
      //   isProcess,
      //   statusList,
      //   isStartUsername,
      //   ...restparames
      // } = _this.searchData;
      _this.isLoading = true;

      const res = await api.getEquipmentMouldList({
        // ..._this.searchData,
        pageNum: pageNum,
        pageSize: _this.paginationOpt.defaultPageSize,
        companyId: _this.compId
        // companyId: 1568,
      });

      _this.isLoading = false;
      if (res.code !== 200) {
        this.$message.error("获取数据失败");
        return;
      }

      this.paginationOpt.total = res.data.total;
      let newObj = res.data.rows;
      this[key] = newObj;
    },

    // 点击每一行的跳转;
    clickSingleRow(record, index) {
      return {
        on: {
          click: () => {
            // 实现跳转;
            let { name, id } = record;
            window.open(
              `/#/assembleTemplateNew?mouldName=${name}&mouldId=${id}`
            );
          }
        }
      };
    },

    // 新建工单
    toAddPage(type,item) {
      if(type == 'copy' && item) {
        this.rowRecord = item
      }
      this.newMouldType = type
      this.isAddTemplateDialog = true;
    },

    detailPartOrder(item) {
      this.detailPartDialog = true;
      this.rowRecord = item;
    },

    // 列表确认收货按钮
    confirmOrder(item) {
      let _this = this;
      this.$Modal.confirm({
        title: "是否确认收货?",
        // onOk() {
        //   let { orderNumber } = item;
        //   _this.deliverGoodsProcessReceive({
        //     orderNumber,
        //     username: _this.userName,
        //     name: _this.name
        //   });
        // },

        onOk: async () => {
          let { orderNumber } = item;
          const res = await api.deliverGoodsProcessReceive({
            orderNumber,
            username: _this.userName,
            name: _this.name
          });

          if (res.code != 200) {
            this.$message.error(`确认收货失败`);
            return;
          }

          _this.getTableData(
            { pageNum: this.paginationOpt.current },
            "tableDataLists"
          );
        },
        onCancel() {}
      });
    },

    // 获取需要导出的数据
    async getDownloadData() {
      let _this = this;
      if (_this.iconLoading == true) {
        return false;
      }
      let total = _this.paginationOpt.total;
      let pageSize = 300;
      let length = Math.ceil(total / pageSize);
      let newLists = [];
      _this.iconLoading = true;
      for (let i = 1; i <= length; i++) {
        let lists = await this.buildDownloadLists({
          pageNum: i,
          pageSize: pageSize
        });
        newLists.push(lists);
      }
      _this.iconLoading = false;
      return [].concat(...newLists);
    },

    async buildDownloadLists(parames) {
      let _this = this;
      let { pageNum, pageSize } = parames;

      const res = await api.deliverGoodsInfoGetAll({
        page: pageNum,
        pageSize,
        ..._this.searchData,
        username: _this.userName
      });

      if (res.code != 200) {
        return;
      }

      let list = buildLists(res.data.content);
      return list;

      function buildLists(lists) {
        return lists.map((item, index) => {
          try {
            let newItem = format(item);
            return newItem;
          } catch (e) {
            console.log(e);
          }
        });
      }

      function format(item) {
        if (item.orderNumber) {
          item.orderNumber = `'${item.orderNumber}'`;
        }
        if (item.kitInformationList) {
          item.kitInformationList = formatLists(item.kitInformationList);
        }
        if (item.status) {
          item.status = formatState(item.status);
        }
        return item;
      }

      function formatState(state) {
        switch (state) {
          case 1:
            return "发货";
          case 2:
            return "收货";
          default:
            break;
        }
      }

      function formatLists(lists) {
        let str = "";
        lists.forEach((item, index) => {
          let { kitType, kitVersion, number } = item;
          str =
            str +
            `零配件${index +
              1}       零配件类型: ${kitType}, 零配件型号: ${kitVersion} , 发货数量: ${number};
          `;
        });
        return str;
      }
    }
  },
  mounted() {
    // 获取useInfo
    getRoleId(this);
    // if (this.role == 17) {
    //   this.tableColumns = columns;
    // } else {
    //   this.tableColumns = filterTableColumns(columns, ["leftExt"]);
    // }
    this.tableColumns = columns;
    this.getTableData({ pageNum: 1 }, "tableDataLists");
  },
  created() {}
};
</script>

<style lang="css" scoped>
@import "./style.css";
.itemWrap {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.itemWrap > .label {
  min-width: 90px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #373737;
  text-align: right;
}

.itemWrap > .separator {
  padding: 0px 4px;
}

.itemWrap > .content {
  width: 100%;
  padding: 0px 1px;
}
.main-title {
  margin-right: 10px;
  font-size: 1.4rem;
  font-weight: bold;
  color: rgb(70, 71, 73);
}
</style>
